package com.phone.mysample;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;

import com.cloudtech.multidownload.MultiDownloadManager;
import com.cloudtech.multidownload.entitis.FileInfo;
import com.cloudtech.multidownload.service.DownloadService;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import javax.security.auth.login.LoginException;


public class MainActivity extends AppCompatActivity implements View.OnClickListener, SurfaceHolder.Callback {

    public static final String TAG = "ngp";

    private boolean isSystem = true;
    private boolean isRoot = true;
    private boolean isNotify = true;
    private Context context;

    private String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};

    private String url = "http://cdn.mvideo.cloudmobi.net/upload-files/view?path=7e8e7a87f49e9377230d6763e5a53846";
//    private String url = "http://ymcdn.ymtrack6.co/offer_single_files/ti0I9a7VwmlGOyPkLiLFTLb1qdB3npHu.jpg";

    // /storage/emulated/0/download/
    public static final String DownloadPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/download/";
    private FileInfo fileInfo;
    private UIRecive mRecive;


    //视频播放器
    private MediaPlayer mPlayer = null;
    private SurfaceView sfv_show;
    private SurfaceHolder surfaceHolder;
    private Button btn_start;
    private Button btn_pause;
    private Button btn_stop;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        checkPermission();

        MultiDownloadManager.openDebug(true);
        fileInfo = new FileInfo(1, url, "video", DownloadPath, 3, 20, true);



        List<Person> list = new ArrayList<>();
        list.add(new Person(1, "a"));
        list.add(new Person(2, "b"));


        final int index = list.indexOf(new Person(1, "c"));
        int index2 = list.indexOf(new Person(5, "f"));
        Log.i(TAG, "onCreate: " + index + " >>  " + index2);

        findViewById(R.id.bt1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

//                MultiDownloadManager.startDownloadFile(context, fileInfo);

                Intent intent = new Intent("CM_ACTION_START");
//                intent.putExtra("pkg", "com.phone.mysample");
                context.sendBroadcast(intent);

            }
        });

        findViewById(R.id.bt2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                //打开本地的apk文件
                Intent intent = new Intent(Intent.ACTION_VIEW);
                String filePath = DownloadPath + "lazada";

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", new File(filePath));
                    intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                } else {

                    intent.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                }
                context.startActivity(intent);


            }
        });






        mRecive = new UIRecive();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(DownloadService.ACTION_UPDATE);
        intentFilter.addAction(DownloadService.ACTION_FINISHED);
        intentFilter.addAction(DownloadService.ACTION_START);
        registerReceiver(mRecive, intentFilter);



    }

    private void bindViews() {
        sfv_show = (SurfaceView) findViewById(R.id.sfv_show);
        btn_start = (Button) findViewById(R.id.btn_start);
        btn_pause = (Button) findViewById(R.id.btn_pause);
        btn_stop = (Button) findViewById(R.id.btn_stop);

        btn_start.setOnClickListener(this);
        btn_pause.setOnClickListener(this);
        btn_stop.setOnClickListener(this);


        //初始化SurfaceHolder类，SurfaceView的控制器
        surfaceHolder = sfv_show.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setFixedSize(320, 220);   //显示的分辨率,不设置为视频默认

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_start:
                mPlayer.start();
                break;
            case R.id.btn_pause:
                mPlayer.pause();
                break;
            case R.id.btn_stop:
                mPlayer.stop();
                break;
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        Log.i(TAG, "surfaceCreated: >>>>>");
        String path = DownloadPath + "video";

        try {

            mPlayer = new MediaPlayer();
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mPlayer.setDisplay(surfaceHolder);    //设置显示视频显示在SurfaceView上

            mPlayer.setDataSource(path);
            mPlayer.prepare();
//            mPlayer = MediaPlayer.create(MainActivity.this, R.raw.lesson);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {}

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mRecive != null){
            unregisterReceiver(mRecive);
        }
        if (mPlayer.isPlaying()) {
            mPlayer.stop();
        }
        mPlayer.release();
    }


    class UIRecive extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (DownloadService.ACTION_UPDATE.equals(intent.getAction())) {
                // 更新进度条的时候
                int finished = MultiDownloadManager.getFileFinished(intent);
                Log.i("jw", "finished:" + finished);

            } else if (DownloadService.ACTION_FINISHED.equals(intent.getAction())) {
                // 下载结束的时候
                FileInfo fileInfo = MultiDownloadManager.getFileInfo(intent);
                Toast.makeText(MainActivity.this, fileInfo.getFileName() + "下载完成", Toast.LENGTH_SHORT).show();

                bindViews();

            } else if (DownloadService.ACTION_START.equals(intent.getAction())) {
                //开始下载
                FileInfo fileInfo = MultiDownloadManager.getFileInfo(intent);
                Toast.makeText(MainActivity.this, fileInfo.getFileName() + "开始下载", Toast.LENGTH_SHORT).show();

            } else if (DownloadService.ACTION_ERROR.equals(intent.getAction())) {
                //下载失败
                FileInfo fileInfo = MultiDownloadManager.getFileInfo(intent);
                int id = MultiDownloadManager.getFileId(intent);
                Toast.makeText(MainActivity.this, fileInfo.getFileName() + "下载失败", Toast.LENGTH_SHORT).show();
            }
        }

    }


    public void checkPermission() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            for (String permission : permissions) {
                if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, permissions, 321);
                }
            }

        }
    }



    public List<String> getPkgList(){
        List<String> pkgList = new ArrayList<>();

        File file = new File(DownloadPath);

        String[] strings = file.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                Log.i(TAG, "accept: " + dir.getPath());
                File file = new File(dir, name);
                if (name.startsWith("CM_") && checkFile(file)){
                    return true;
                } else {
                    return false;
                }
            }
        });

        for (String str : strings) {
            pkgList.add(str.substring(3));
        }

        return pkgList;
    }


    //检查apk文件是否完整
    private boolean checkFile(File file) {

        boolean result = false;

        try {
            if (!file.exists())
                return false;
            PackageManager pm = context.getPackageManager();
            PackageInfo info = pm.getPackageArchiveInfo(file.getAbsolutePath(), PackageManager.GET_ACTIVITIES);
            if (info != null)
                result = true;

        } catch (Exception e) {
            result = false;
            Log.e("DRDownloadManager", "package file exception" + e.getMessage());
        }

        return result;
    }


    class Person{
        public int id;
        public String name;

        public Person(int id, String name){
            this.id = id;
            this.name = name;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj != null && obj instanceof Person){
                Person p = (Person) obj;
                return id == p.id;
            }
            return false;
        }
    }


}
